/**
 * 项目名：	Rumba Plan
 * 
 * 版权所有(C)，上海海鼎信息工程股份有限公司，2006，所有权利保留。
 * 
 * 文件名：	ViewUser.java
 * 模块说明：	
 * 修改历史：
 * 2006-9-13 - lxm - 创建。
 */
package com.hd123.rumba.action.user;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import net.sf.hibernate.HibernateException;

import com.hd123.rumba.action.log.ViewEntityLogs;
import com.hd123.rumba.domain.CDomain;
import com.hd123.rumba.domain.biz.IBDomainMgr;
import com.hd123.rumba.domain.biz.SDomain;
import com.hd123.rumba.exception.BusinessException;
import com.hd123.rumba.log.ActionLogger;
import com.hd123.rumba.request.ActionAbstractImpl;
import com.hd123.rumba.request.ActionConstants;
import com.hd123.rumba.request.JspLib;
import com.hd123.rumba.runtime.FormatSettings;
import com.hd123.rumba.runtime.NamingMgr;
import com.hd123.rumba.runtime.OperateContext;
import com.hd123.rumba.sql.biz.BResultPage;
import com.hd123.rumba.sql.biz.BSQLSubquery;
import com.hd123.rumba.user.CPermission;
import com.hd123.rumba.user.CUser;
import com.hd123.rumba.user.IPermissionMgr;
import com.hd123.rumba.user.biz.BBasePermAssign;
import com.hd123.rumba.user.biz.BPermGroupAssign;
import com.hd123.rumba.user.biz.BPermissionCommand;
import com.hd123.rumba.user.biz.BRole;
import com.hd123.rumba.user.biz.BUser;
import com.hd123.rumba.user.biz.IBPermAgent;
import com.hd123.rumba.user.biz.IBRoleMgr;
import com.hd123.rumba.user.biz.IBUserMgr;
import com.hd123.rumba.user.biz.SRole;
import com.hd123.rumba.util.ClassifiedHashtable;

/**
 * 用户 | Action | 基类
 * 
 * @author lxm
 * 
 */
public abstract class BaseViewUser extends ActionAbstractImpl {

  /* Templates */
  protected static final String TEMPLATE_LIST = "user/UsersList.jsp";
  protected static final String TEMPLATE_FILTER = "user/UsersFilter.jsp";
  protected static final String TEMPLATE_CREATE = "user/UserCreate.jsp";
  protected static final String TEMPLATE_EDIT = "user/UserEdit.jsp";
  protected static final String TEMPLATE_VIEW = "user/UserView.jsp";
  protected static final String TEMPLATE_ROLESEDIT = "user/UserRolesEdit.jsp";
  protected static final String TEMPLATE_PERMISSIONSEDIT = "user/UserPermissionsEdit.jsp";
  protected static final String TEMPLATE_BROWSERDEF = "user/UserBrowserDef.jsp";

  public String list() throws Exception {
    SDomain domain = getFormDomain();
    String isRecycleStr = (String) dd.getFormValue("isRecycle");
    if (isRecycleStr == null)
      isRecycleStr = "FALSE";
    Boolean isRecycle = "TRUE".equalsIgnoreCase(isRecycleStr) ? Boolean.TRUE : Boolean.FALSE;
    UserFilter filter = getFormFilter();
    return this.showListSafely(filter, domain, isRecycle);
  }

  public String filter() throws Exception {
    SDomain domain = getFormDomain();
    String isRecycleStr = (String) dd.getFormValue("isRecycle");
    if (isRecycleStr == null)
      isRecycleStr = "FALSE";
    Boolean isRecycle = "TRUE".equalsIgnoreCase(isRecycleStr) ? Boolean.TRUE : Boolean.FALSE;
    String permId = this.getPermission(ViewUser.FUNCTION_VIEW, domain.getUuid(), isRecycle);
    if (permId != null && !this.getCurrentUser().hasPermission(permId))
      return ActionConstants.NOACCESS;

    UserFilter filter = getFormFilter();

    dd.put("filter", filter);
    dd.put("domain", domain);
    dd.put("isRecycle", isRecycle);
    dd.put("viewRoleName", getViewRoleName());
    dd.setWorkingTemplate(TEMPLATE_FILTER);
    return ActionConstants.APPLICATIONFRAME;
  }

  public String create() throws Exception {
    SDomain domain = getFormDomain();
    BUser user = getBUserMgr().createUser(domain.getUuid());

    return showDetailSafely(user, JspLib.VALUE_FORMSTATE_CREATE, true);
  }

  public String view() throws Exception {
    String uuid = (String) dd.getFormValue("user_uuid");
    if (uuid == null)
      throw new Exception("缺少必须的参数user_uuid。");
    String tabView = (String) dd.getFormValue("tabView");
    if (tabView == null)
      tabView = "tvRoles";

    BUser user = getBUserMgr().loadUser(uuid);

    dd.put("tabView", tabView);
    return showDetailSafely(user, JspLib.VALUE_FORMSTATE_VIEW, true);
  }

  public String edit() throws Exception {
    String uuid = (String) dd.getFormValue("user_uuid");
    if (uuid == null)
      throw new Exception("缺少必须的参数user_uuid。");
    String ocaStr = (String) dd.getFormValue("user_oca");
    if (ocaStr == null)
      throw new Exception("缺少必须的参数user_oca。");
    long oca = Long.valueOf(ocaStr).longValue();

    BUser user = getBUserMgr().loadUser(uuid);

    this.checkOca(user, oca, CUser.CAPTION_CLASS);

    return showDetailSafely(user, JspLib.VALUE_FORMSTATE_EDIT, true);
  }

  public String save() throws Exception {
    String formState = (String) dd.getFormValue("formState");
    String uuid = (String) dd.getFormValue("user_uuid");
    if ("".equals(uuid))
      uuid = null;
    BUser user = null;
    boolean isNew;

    try {
      if (uuid == null) {
        String domainUuid = (String) dd.getFormValue("user_domain_uuid");
        user = getBUserMgr().createUser(domainUuid);
        isNew = true;
      } else {
        user = getBUserMgr().loadUser(uuid);
        isNew = false;
      }
      readFormUser(user, formState);
      if (isNew)
        logger.info(ActionLogger.EVENT_SAVENEW, user.getNameCode());
      else
        logger.info(ActionLogger.EVENT_SAVE, CUser.CAPTION_UUID + "=\"" + user.getUuid() + "\"。");
      if (!dd.isFormValid())
        return showDetailSafely(user, formState, false);
      ClassifiedHashtable h = getBUserMgr().saveUserT(user, new OperateContext(getCurrentUser()));
      if (h != null && h.size() > 0) {
        dd.addInvalidFormValues("user_", h);
        // oca错误需要特殊处理：取消所做的修改。
        if (h.getMessage("oca") != null && uuid != null) {
          // 断言条件uuid != null，即非新增状态。
          dd.putFormValue("user_uuid", user.getUuid());
          return view();
        } else
          return showDetailSafely(user, formState, false);
      }
    } catch (Exception e) {
      dd.addErrorText(e.getMessage());
      return showDetailSafely(user, formState, false);
    }

    dd.putFormValue("user_uuid", user.getUuid());
    dd.addHint(CUser.CAPTION_CLASS + "已保存。");
    return view();
  }

  public String delete() throws Exception {
    String uuid = (String) dd.getFormValue("user_uuid");
    if (uuid == null)
      throw new Exception("缺少必须的参数user_uuid。");
    String ocaStr = (String) dd.getFormValue("user_oca");
    if (ocaStr == null)
      throw new Exception("缺少必须的参数user_oca。");
    long oca = Long.valueOf(ocaStr).longValue();

    try {
      delete2(uuid, oca);
      dd.addHint(CUser.CAPTION_CLASS + "已被删除。");
    } catch (Exception e) {
      dd.addErrorText(e.getMessage());
    }
    BUser user = getBUserMgr().loadUser(uuid);

    return showDetailSafely(user, JspLib.VALUE_FORMSTATE_VIEW, false);
  }

  public String undelete() throws Exception {
    String uuid = (String) dd.getFormValue("user_uuid");
    if (uuid == null)
      throw new Exception("缺少必须的参数user_uuid。");
    String ocaStr = (String) dd.getFormValue("user_oca");
    if (ocaStr == null)
      throw new Exception("缺少必须的参数user_oca。");
    long oca = Long.valueOf(ocaStr).longValue();

    try {
      undelete2(uuid, oca);
      dd.addHint(CUser.CAPTION_CLASS + "已被恢复删除。");
    } catch (Exception e) {
      dd.addErrorText(e.getMessage());
    }
    BUser user = getBUserMgr().loadUser(uuid);

    return showDetailSafely(user, JspLib.VALUE_FORMSTATE_VIEW, false);
  }

  public String editUserRoles() throws Exception {
    logger.info(ActionLogger.EVENT_EDIT, "编辑" + CUser.CAPTION_CLASS + CUser.CAPTION_ROLES + "。");

    String uuid = (String) dd.getFormValue("user_uuid");
    if (uuid == null)
      throw new Exception("缺少必须的参数user_uuid。");
    String ocaStr = (String) dd.getFormValue("user_oca");
    if (ocaStr == null)
      throw new Exception("缺少必须的参数user_oca。");
    long oca = Long.valueOf(ocaStr).longValue();

    BUser user = getBUserMgr().loadUser(uuid);

    this.checkOca(user, oca, CUser.CAPTION_CLASS);

    return showUserRolesEditSafely(user);
  }

  public String saveUserRoles() throws Exception {
    String uuid = (String) dd.getFormValue("user_uuid");
    if (uuid == null)
      throw new Exception("缺少必须的参数user_uuid。");
    String ocaStr = (String) dd.getFormValue("user_oca");
    if (ocaStr == null)
      throw new Exception("缺少必须的参数user_oca。");
    long oca = Long.valueOf(ocaStr).longValue();

    IBRoleMgr roleMgr = (IBRoleMgr) NamingMgr.getInstance().lookupMgr(IBRoleMgr.class);
    List<SRole> list = new ArrayList();
    Iterator roleUuids = dd.createFormSelectedValuesIterator("user_role_uuids");
    while (roleUuids.hasNext()) {
      String roleUuid = (String) roleUuids.next();
      SRole role = (SRole) roleMgr.getRole(roleUuid, SRole.class);
      list.add(role);
    }

    try {
      ClassifiedHashtable h = getBUserMgr().saveUserRolesT(uuid, list,
          new OperateContext(this.getCurrentUser()), oca);
      if (h != null && h.size() > 0) {
        dd.addInvalidFormValues("user_", h);
        return showUserRolesEditSafely(uuid);
      }
    } catch (Exception e) {
      dd.addErrorText(e.getMessage());
      return showUserRolesEditSafely(uuid);
    }

    BUser user = (BUser) getBUserMgr().getUser(uuid, BUser.class);
    dd.put("tabView", "tvRoles");
    return showDetailSafely(user, JspLib.VALUE_FORMSTATE_VIEW, false);
  }

  public String editUserPermissions() throws Exception {
    logger.info(ActionLogger.EVENT_EDIT, "编辑" + CUser.CAPTION_CLASS + "拥有的"
        + CPermission.CAPTION_CLASS + "。");

    String uuid = (String) dd.getFormValue("user_uuid");
    if (uuid == null)
      throw new Exception("缺少必须的参数user_uuid。");
    String ocaStr = (String) dd.getFormValue("user_oca");
    if (ocaStr == null)
      throw new Exception("缺少必须的参数user_oca。");
    long oca = Long.valueOf(ocaStr).longValue();

    BUser user = getBUserMgr().loadUser(uuid);

    this.checkOca(user, oca, CUser.CAPTION_CLASS);

    return showUserPermissionsEditSafely(user);
  }

  public String saveUserPermissions() throws Exception {
    String uuid = (String) dd.getFormValue("user_uuid");
    if (uuid == null)
      throw new Exception("缺少必须的参数user_uuid。");
    String ocaStr = (String) dd.getFormValue("user_oca");
    if (ocaStr == null)
      throw new Exception("缺少必须的参数user_oca。");
    long oca = Long.valueOf(ocaStr).longValue();

    logger.info(ActionLogger.EVENT_SAVE, "修改拥有的" + CPermission.CAPTION_CLASS + "。");
    List<BPermissionCommand> cmdList = getFormPermissionCommands();
    IBPermAgent agent = getBUserMgr().createUserPermAgent(uuid);
    try {
      agent.executeCommandsT(cmdList, new OperateContext(getCurrentUser()), oca);
    } catch (Exception e) {
      e.printStackTrace();
      dd.addErrorText(e.getMessage());
      return showUserPermissionsEditSafely(uuid);
    }

    BUser user = getBUserMgr().loadUser(uuid);
    dd.addHint(CUser.CAPTION_CLASS + "拥有的" + CPermission.CAPTION_CLASS + "已保存。");
    dd.put("tabView", "tvPermissions");
    return showDetailSafely(user, JspLib.VALUE_FORMSTATE_VIEW, false);
  }

  public String browse() throws Exception {
    dd.put("entityCaption", CUser.CAPTION_CLASS);
    dd.put("entityIcon", "rumba/images/user/user_small.gif");
    dd.setWorkingTemplate(TEMPLATE_BROWSERDEF);
    return ActionConstants.BROWSERFRAME;
  }

  /**
   * 用于汇总页面用户列表的查询。
   * 
   * @param bsq
   * @param pageSize
   * @param page
   * @return
   * @throws Exception
   */
  public BResultPage queryList(BSQLSubquery bsq, int pageSize, int page) throws Exception {
    try {
      addForceFilter(bsq);
      return this.query(bsq, pageSize, page);
    } catch (Exception e) {
      this.reportError("", e);
      throw e;
    }
  }

  /**
   * 删除指定的用户。
   * 
   * @param uuid
   *          被删除用户的uuid。
   * @param oca
   * @throws Exception
   */
  public void delete2(String uuid, long oca) throws Exception {
    try {
      logger.info(ActionLogger.EVENT_DELETE, "uuid=" + uuid);
      getBUserMgr().deleteUserT(uuid, new OperateContext(getCurrentUser()), oca);
    } catch (Exception e) {
      this.reportError("", e);
      throw e;
    }
  }

  /**
   * 恢复删除指定的用户。
   * 
   * @param uuid
   *          被恢复删除用户的uuid。
   * @param oca
   * @throws Exception
   */
  public void undelete2(String uuid, long oca) throws Exception {
    try {
      logger.info(ActionLogger.EVENT_UNDELETE, "uuid=" + uuid);
      getBUserMgr().undeleteUserT(uuid, new OperateContext(getCurrentUser()), oca);
    } catch (Exception e) {
      this.reportError("", e);
      throw e;
    }
  }

  /**
   * 启用指定的用户。
   * 
   * @param uuid
   *          被启用的用户的uuid。
   * @param oca
   * @throws Exception
   */
  public void online2(String uuid, long oca) throws Exception {
    try {
      logger.info("启用", "uuid=" + uuid);
      getBUserMgr().onlineUserT(uuid, new OperateContext(getCurrentUser()), oca);
    } catch (Exception e) {
      this.reportError("", e);
      throw e;
    }
  }

  /**
   * 禁用指定的用户。
   * 
   * @param uuid
   *          被禁用的用户的uuid。
   * @param oca
   * @throws Exception
   */
  public void offline2(String uuid, long oca) throws Exception {
    try {
      logger.info("禁用", "uuid=" + uuid);
      getBUserMgr().offlineUserT(uuid, new OperateContext(getCurrentUser()), oca);
    } catch (Exception e) {
      this.reportError("", e);
      throw e;
    }
  }

  public BPermGroupAssign getGlobalPermGroups(Boolean projection, String userUuid) throws Exception {
    try {
      IBPermAgent agent = null;
      if (projection.booleanValue())
        agent = getBUserMgr().createUserProjectivePermAgent(userUuid);
      else
        agent = getBUserMgr().createUserPermAgent(userUuid);
      return agent.getGlobalPermGroup();
    } catch (Exception e) {
      this.reportError("", e);
      throw e;
    }
  }

  public List<BPermGroupAssign> getCFVPermGroups(Boolean projection, String userUuid)
      throws Exception {
    try {
      IBPermAgent agent = null;
      if (projection.booleanValue())
        agent = getBUserMgr().createUserProjectivePermAgent(userUuid);
      else
        agent = getBUserMgr().createUserPermAgent(userUuid);
      return agent.getCFVPermGroups();
    } catch (Exception e) {
      this.reportError("", e);
      throw e;
    }
  }

  public List<BPermGroupAssign> getProviderPermGroups(Boolean projection, String userUuid,
      String cfvUuid) throws Exception {
    try {
      IBPermAgent agent = null;
      if (projection.booleanValue())
        agent = getBUserMgr().createUserProjectivePermAgent(userUuid);
      else
        agent = getBUserMgr().createUserPermAgent(userUuid);
      return agent.getProviderPermGroups(cfvUuid);
    } catch (Exception e) {
      this.reportError("", e);
      throw e;
    }
  }

  public List<BBasePermAssign> getPermissions(Boolean projection, String userUuid, String cfvUuid,
      String providerClassName) throws Exception {
    try {
      IBPermAgent agent = null;
      if (projection.booleanValue())
        agent = getBUserMgr().createUserProjectivePermAgent(userUuid);
      else
        agent = getBUserMgr().createUserPermAgent(userUuid);
      return agent.getPermissions(cfvUuid, providerClassName);
    } catch (Exception e) {
      this.reportError("", e);
      throw e;
    }
  }

  /**
   * 根据功能等信息取得权限ID。
   * 
   * @param functionName
   *          功能名，取值为类似“FUNCTION_*”的常量。
   * @param domainUuid
   *          指定用户所在域的uuid。
   * @param isRecycle
   *          是否是回收站。
   * @return 返回权限表达式，若没有权限对应则返回null。
   * @throws BusinessException
   * @throws HibernateException
   */
  public abstract String getPermission(String functionName, String domainUuid, Boolean isRecycle)
      throws BusinessException, HibernateException;

  /**
   * 取得对应的角色View名称。
   * 
   * @return
   */
  protected abstract String getViewRoleName();

  /**
   * 添加对用户的强制筛选条件。
   * 
   * @param bsq
   */
  protected abstract void addForceFilter(BSQLSubquery bsq) throws BusinessException,
      HibernateException;

  private IBUserMgr userMgr = null;

  protected IBUserMgr getBUserMgr() throws BusinessException {
    if (userMgr == null)
      userMgr = (IBUserMgr) NamingMgr.getInstance().lookupMgr(IBUserMgr.class);
    return userMgr;
  }

  private SDomain getFormDomain() throws Exception {
    String domainUuid = (String) dd.getFormValue("domain_uuid");
    if (domainUuid == null)
      domainUuid = dd.getCurrentDomain().getUuid();
    IBDomainMgr dmMgr = (IBDomainMgr) NamingMgr.getInstance().lookupMgr(IBDomainMgr.class);
    SDomain dm = dmMgr.getDomain(domainUuid);
    if (dm == null)
      throw new BusinessException("找不到指定的" + CDomain.CAPTION_CLASS + "(" + domainUuid + ")。");
    return dm;
  }

  private UserFilter getFormFilter() throws Exception {
    UserFilter filter = new UserFilter();
    filter.setCodeLike((String) dd.getFormValue("filter_codeLike"));
    filter.setNameLike((String) dd.getFormValue("filter_nameLike"));
    String online = (String) dd.getFormValue("filter_online");
    if ("".equals(online))
      online = null;
    if (online != null)
      filter.setOnline(new Integer(online));
    String hasRoleUuid = (String) dd.getFormValue("filter_hasRole");
    if ("".equals(hasRoleUuid))
      hasRoleUuid = null;
    if (hasRoleUuid != null) {
      IBRoleMgr roleMgr = (IBRoleMgr) NamingMgr.getInstance().lookupMgr(IBRoleMgr.class);
      SRole role = (SRole) roleMgr.getRole(hasRoleUuid, SRole.class);
      filter.setHasRole(role);
    }
    return filter;
  }

  /**
   * 检查用户权限，尝试显示列表页面。
   * <p>
   * 
   * 如果要求显示的是正常的列表页面，则先检查是否具有正常查看权，若没有，则显示NOACCESS页面；<br>
   * 如果要求显示的是回收站的列表页面，则先检查是否有回收站查看权，若没有，则再尝试显示正常的列表页面，若还没有，则显示NOACCESS页面。
   * 
   * @param filter
   *          指定约束条件对象。
   * @param domain
   *          指定域。
   * @param isRecycle
   *          指定是否查看回收站。
   * @return
   * @throws Exception
   */
  private String showListSafely(UserFilter filter, SDomain domain, Boolean isRecycle)
      throws Exception {
    String permId = this.getPermission(ViewUser.FUNCTION_VIEW, domain.getUuid(), isRecycle);
    if (!this.getCurrentUser().hasPerm(permId)) {
      if (isRecycle.booleanValue())
        return showListSafely(filter, domain, Boolean.valueOf(!isRecycle.booleanValue()));
      else
        return showNoAccess();
    }
    return showList(filter, domain, isRecycle);
  }

  private String showList(UserFilter filter, SDomain domain, Boolean isRecycle) throws Exception {
    if (!isRecycle.booleanValue())
      logger.info(ActionLogger.EVENT_LIST, null);
    else
      logger.info(ActionLogger.EVENT_RECYCLE_LIST, null);

    dd.put("filter", filter);
    dd.put("domain", domain);
    dd.put("isRecycle", isRecycle);
    this.putFormPermissions(domain, isRecycle);
    dd.setWorkingTemplate(TEMPLATE_LIST);
    return ActionConstants.APPLICATIONFRAME;
  }

  /**
   * 尝试显示明细页面。
   * <p>
   * 
   * 若指定显示的是编辑页面，将尝试检查是否具有编辑权限，若没有则尝试显示查看页面。<br>
   * 当检查权限的时候，若当前用户缺少访问指定页面的权限，将尝试显示列表页面（通过调用{@link #showList()}）。
   * 
   * @param user
   *          指定显示的用户。
   * @param formState
   *          指定页面状态。
   * @param directly
   *          指定是否直接调用。
   * @return
   * @throws Exception
   */
  private String showDetailSafely(BUser user, String formState, boolean directly) throws Exception {
    if (user == null)
      user = getBUserMgr().createUser((String) dd.getFormValue("domain_uuid"));
    Boolean isRecycle = Boolean.valueOf(CUser.VALUE_STATE_DELETED.equals(user.getState()));
    String funcName = null;
    if (JspLib.VALUE_FORMSTATE_CREATE.equals(formState))
      funcName = ViewUser.FUNCTION_CREATE;
    else if (JspLib.VALUE_FORMSTATE_EDIT.equals(formState))
      funcName = ViewUser.FUNCTION_EDIT;
    else if (JspLib.VALUE_FORMSTATE_VIEW.equals(formState))
      funcName = ViewUser.FUNCTION_VIEW;
    else
      throw new Exception("未知的参数formState取值(" + formState + ")。");
    String permId = this.getPermission(funcName, user.getDomain().getUuid(), isRecycle);
    if (!this.getCurrentUser().hasPerm(permId)) {
      if (directly)
        dd.addErrorText("您缺少对指定" + CUser.CAPTION_CLASS + "进行" + funcName + "的权限。");
      if (JspLib.VALUE_FORMSTATE_EDIT.equals(formState))
        return showDetailSafely(user, JspLib.VALUE_FORMSTATE_VIEW, false);
      else
        return showListSafely(this.getFormFilter(), user.getDomain(), isRecycle);
    }

    return showDetail(user, formState);
  }

  private String showDetail(BUser user, String formState) throws Exception {
    boolean isRecycle = CUser.VALUE_STATE_DELETED.equals(user.getState());
    dd.put("user", user);

    IPermissionMgr permMgr = (IPermissionMgr) NamingMgr.getInstance().lookupMgr(
        IPermissionMgr.class);
    dd.put("am", permMgr.createFieldsAccessMode(getCurrentUser(), CUser.class));

    this.putFormPermissions(user.getDomain(), Boolean.valueOf(isRecycle));
    dd.putFormValue(JspLib.ID_FORMSTATE, formState);
    if (JspLib.VALUE_FORMSTATE_CREATE.equals(formState)) {
      logger.info(ActionLogger.EVENT_CREATE, null);
      validateRequiredFields(user);
      dd.setWorkingTemplate(TEMPLATE_CREATE);
    } else if (JspLib.VALUE_FORMSTATE_EDIT.equals(formState)) {
      logger.info(ActionLogger.EVENT_EDIT, null);
      dd.setWorkingTemplate(TEMPLATE_EDIT);
    } else {
      logger.info(ActionLogger.EVENT_VIEW, null);
      dd.setWorkingTemplate(TEMPLATE_VIEW);
      ViewEntityLogs.preloadJSP(dd, user.getUuid(), CUser.STATEMAP);
    }
    return ActionConstants.APPLICATIONFRAME;
  }

  private void readFormUser(BUser user, String formState) throws Exception {
    boolean isRootAdmin = false;
    if (CDomain.VALUE_ID_ROOT.equals(this.getCurrentDomain().getCode())
        && CUser.VALUE_LOGIN_ROOT_ADMIN.equalsIgnoreCase(user.getLogin()))
      isRootAdmin = true;
    boolean isSelf = false;
    if (this.getCurrentUser().getUuid().equals(user.getUuid()))
      isSelf = true;

    String ocaStr = (String) dd.getFormValue("user_oca");
    user.setOca((new Long(ocaStr)).longValue());
    if (!isRootAdmin)
      user.setLogin((String) dd.validateFormValue("user_login", null, true, user.getLogin(),
          CUser.CAPTION_LOGIN));
    user.setName((String) dd.validateFormValue("user_name", null, true, user.getName(),
        CUser.CAPTION_NAME));
    boolean pwdValid = JspLib.VALUE_FORMSTATE_CREATE.equals(formState);
    user.setPassword((String) dd.validateFormValue("user_password", null, pwdValid, user
        .getPassword(), CUser.CAPTION_PASSWORD));
    user.setPasswordConfirm((String) dd.validateFormValue("user_passwordConfirm", null, pwdValid,
        user.getPasswordConfirm(), CUser.CAPTION_PASSWORD + "确认"));
    if (!isRootAdmin && !isSelf)
      user.setOnline(new Boolean(dd.getFormValues().containsKey("user_online")));
    user.setValidFrom((Date) dd.validateFormValue("user_validFrom", FormatSettings.VALID_DATE,
        false, user.getValidFrom(), CUser.CAPTION_VALIDFROM));
    user.setValidTo((Date) dd.validateFormValue("user_validTo", FormatSettings.VALID_DATE, false,
        user.getValidTo(), CUser.CAPTION_VALIDTO));
    user.setUseToken(new Boolean(dd.getFormValues().containsKey("user_useToken")));
    user.setTokenSn((String) dd.validateFormValue("user_tokenSn", null, user.getUseToken()
        .booleanValue(), user.getTokenSn(), CUser.CAPTION_TOKENSN));
    user.setTokenPin((String) dd.validateFormValue("user_tokenPin", null, user.getUseToken()
        .booleanValue(), user.getTokenPin(), CUser.CAPTION_TOKENPIN));
    user.setRemark((String) dd.validateFormValue("user_remark", null, false, user.getRemark(),
        CUser.CAPTION_REMARK));
  }

  private String showUserRolesEditSafely(String userUuid) throws Exception {
    BUser user = getBUserMgr().loadUser(userUuid);
    return showUserRolesEditSafely(user);
  }

  private String showUserRolesEditSafely(BUser user) throws Exception {
    String permId = this.getPermission(ViewUser.FUNCTION_EDIT, user.getDomain().getUuid(), Boolean
        .valueOf(CUser.VALUE_STATE_DELETED.equals(user.getState())));
    if (!this.getCurrentUser().hasPerm(permId)) {
      dd.addErrorText("您缺少对指定" + CUser.CAPTION_CLASS + "进行" + ViewUser.FUNCTION_EDIT + "的权限。");
      return this.showDetailSafely(user, JspLib.VALUE_FORMSTATE_VIEW, false);
    }
    return showUserRolesEdit(user);
  }

  private String showUserRolesEdit(BUser user) throws Exception {
    List<SRole> userRoles = getBUserMgr().loadUserRoles(user.getUuid());
    IBRoleMgr roleMgr = (IBRoleMgr) NamingMgr.getInstance().lookupMgr(IBRoleMgr.class);
    List<BRole> allRoles = roleMgr.getAllRoles(user.getDomain().getUuid());

    dd.put("user", user);
    dd.put("userRoles", userRoles);
    dd.put("allRoles", allRoles);
    dd.setWorkingTemplate(TEMPLATE_ROLESEDIT);
    return ActionConstants.APPLICATIONFRAME;
  }

  private String showUserPermissionsEditSafely(String userUuid) throws Exception {
    BUser user = getBUserMgr().loadUser(userUuid);
    return showUserPermissionsEditSafely(user);
  }

  private String showUserPermissionsEditSafely(BUser user) throws Exception {
    String permId = this.getPermission(ViewUser.FUNCTION_EDIT, user.getDomain().getUuid(), Boolean
        .valueOf(CUser.VALUE_STATE_DELETED.equals(user.getState())));
    if (!this.getCurrentUser().hasPerm(permId)) {
      dd.addErrorText("您缺少对指定" + CUser.CAPTION_CLASS + "进行" + ViewUser.FUNCTION_EDIT + "的权限。");
      return showDetailSafely(user, JspLib.VALUE_FORMSTATE_VIEW, false);
    }
    return showUserPermissionsEdit(user);
  }

  private String showUserPermissionsEdit(BUser user) throws Exception {
    dd.put("user", user);
    dd.setWorkingTemplate(TEMPLATE_PERMISSIONSEDIT);
    return ActionConstants.APPLICATIONFRAME;
  }

  private List<BPermissionCommand> getFormPermissionCommands() throws Exception {
    List<BPermissionCommand> cmdList = new ArrayList();
    Iterator keyIterator = dd.createFormPrefixedKeysIterator("ptree_commands_");
    List<String> keys = new ArrayList();
    while (keyIterator.hasNext())
      keys.add((String) keyIterator.next());
    Collections.sort(keys);
    for (int i = 0; i < keys.size(); i++) {
      String key = keys.get(i);
      String value = (String) dd.getFormValue("ptree_commands_" + key);
      String[] items = value.split(";");
      BPermissionCommand cmd = new BPermissionCommand();
      if (!"".equals(items[0]))
        cmd.setCartFunctionViewUuid(items[0]);
      if (!"".equals(items[1]))
        cmd.setProviderClassName(items[1]);
      if (!"".equals(items[2]))
        cmd.setFieldCaption(items[2]);
      if (!"".equals(items[3]))
        cmd.setPermissionCode(items[3]);
      if ("".equals(items[4]))
        continue;
      cmd.setCommand(new Integer(items[4]));
      cmdList.add(cmd);
    }
    return cmdList;
  }

  private void putFormPermissions(SDomain domain, Boolean isRecycle) throws BusinessException,
      HibernateException {
    String permId = null;
    permId = this.getPermission(ViewUser.FUNCTION_CREATE, domain.getUuid(), isRecycle);
    if (permId != null)
      dd.put("permissionCreate", permId);
    permId = this.getPermission(ViewUser.FUNCTION_DELETE, domain.getUuid(), isRecycle);
    if (permId != null)
      dd.put("permissionDelete", permId);
    permId = this.getPermission(ViewUser.FUNCTION_UNDELETE, domain.getUuid(), isRecycle);
    if (permId != null)
      dd.put("permissionUndelete", permId);
    permId = this.getPermission(ViewUser.FUNCTION_VIEW, domain.getUuid(), isRecycle);
    if (permId != null)
      dd.put("permissionView", permId);
    permId = this.getPermission(ViewUser.FUNCTION_EDIT, domain.getUuid(), isRecycle);
    if (permId != null)
      dd.put("permissionEdit", permId);
    permId = this.getPermission(ViewUser.FUNCTION_VIEW, domain.getUuid(), new Boolean(!isRecycle
        .booleanValue()));
    if (permId != null)
      dd.put("permissionAnotherView", permId);
  }

  private void validateRequiredFields(BUser user) throws BusinessException {
    dd.validateRequiredFieldPermission("user_login", CUser.PERMISSION_FA_LOGIN, user.getLogin(),
        CUser.CAPTION_LOGIN);
    dd.validateRequiredFieldPermission("user_name", CUser.PERMISSION_FA_NAME, user.getName(),
        CUser.CAPTION_NAME);
    dd.validateRequiredFieldPermission("user_password", CUser.PERMISSION_FA_PASSWORD, user
        .getPassword(), CUser.CAPTION_PASSWORD);
    dd.validateRequiredFieldPermission("user_passwordConfirm", CUser.PERMISSION_FA_PASSWORD, user
        .getPasswordConfirm(), CUser.CAPTION_PASSWORD + "确认");
  }
}
